package cn.alf.ssh.mlxt.dao.hibernateImpl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import cn.alf.ssh.mlxt.dao.UserDao;
import cn.alf.ssh.mlxt.domain.User;

@Transactional
public class UserDaoHImpl implements UserDao {
	@Resource
	private SessionFactory sessionFactory;

	@Override
	public void add(User user) {
		// must be it,not use openSession();
		sessionFactory.getCurrentSession().persist(user);
	}

	@Override
	public void delete(User user) {
		sessionFactory.getCurrentSession().delete(user);
	}

	@Override
	@Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
	public User getUserById(int id) {
		return (User) sessionFactory.getCurrentSession().get(User.class, id);
	}

	@SuppressWarnings("unchecked")
	@Override
	@Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
	public List<User> getUserByName(String name) {
		Query query = sessionFactory.getCurrentSession().createQuery(
						"from cn.alf.ssh.mlxt.domain.User as user where user.name = :name");
		query.setString("name", name);
		return query.list();
	}

	@Override
	public void update(User user) {
		sessionFactory.getCurrentSession().merge(user);
	}

}
